<?php 
class X_mysql extends X{
    public $host;
    public $user;
    public $password;
    public $database;
    public $flags;
    public $charset;
    public $link;
    public $connectionID=null;
    public $connected= false;
    
    public function __construct($host,$user=null,$password=null,$database=null,$flags=null,$charset=null){
        if(is_array($host)){
            $login= $host;
            $host= $login['host'];
            if($user!==null){
                $this->connectionID= $user;
                $user= null;
            }
            if(isset($login['user']))     $user=     $login['user'];
            if(isset($login['password'])) $password= $login['password'];
            if(isset($login['database'])) $database= $login['database'];
            if(isset($login['flags']))    $flags=    $login['flags'];
            if(isset($login['charset']))  $charset=  $login['charset'];
        }
        $this->host= $host;
        $this->user= $user;
        $this->password= $password;
        $this->database= $database;
        $this->flags= $flags;
        $this->charset= ($charset===null)? X_config::$mysql_charset : $charset;
        $this->connect();
    }
    
    public function close(){
        $this->connected= false;
        mysql_close($this->link);
        X_options::$mysql_connections[$this->connectionID]= null;
    }
    
    public function connect(){
        if(!empty($this->host) && !empty($this->user)){
            if(($this->link= mysql_connect($this->host, $this->user, $this->password, true, $this->flags))){
                if($this->connectionID===null)$this->connectionID= count(X_options::$mysql_connections);
                X_options::$mysql_connections[$this->connectionID]= $this;
                if($this->database!=null){
                    while(!mysql_select_db($this->database, $this->link))if(!$this->createDatabase($this->database))exit;
                }
                mysql_set_charset($this->charset, $this->link);
                $this->connected= true;
                return $this->link;
            }
        }
        return false;
    }
    
    public function __toString() {
        return ($this->link)? "Connected with ".$this->link:"NOT CONNECTED";
    }
    
    public function select_db($database){
        $this->database= $database;
        return mysql_select_db($this->database, $this->link);
    }
    
    public function update($table,$values,$cond=null,$escapedVal=null,$escapedVal2=null){
        $db= new X_mysql_query($table,$this->link);
        $db->update($values);
        if($cond!==null)$db->where($cond,$escapedVal,$escapedVal2);
        return $db->execute();
    }
    
    public function delete($table,$cond=null,$escapedVal=null,$escapedVal2=null){
        $db= new X_mysql_query($table,$this->link);
        if($cond!==null)$db->where($cond,$escapedVal,$escapedVal2);
        return $db->delete()->execute();
    }
    
    public function lastInsertId(){
        return mysql_insert_id($this->link);
    }
    
    public function insert($table,$values){
        $db= new X_mysql_query($table,$this->link);
        return $db->insert($values)->execute();
    }
    
    public function select($select,$table,$where=null,$order=null,$limit=null){
        $db= new X_mysql_query($table,$this->link);
        if($where!==null)$db->where($where);
        if($order!==null)$db->order($order);
        if($limit!==null)$db->limit($limit);
        return $db->select()->fetchAll();
    }
    
    public function selectRow($select,$table,$where=null,$order=null){
        $db= new X_mysql_query($table,$this->link);
        if($where!==null)$db->where($where);
        if($order!==null)$db->order($order);
        return $db->select()->fetchRow();
    }
    
    public function selectOne($field,$table,$where=null,$order=null,$start=0){
        $db= new X_mysql_query($table,$this->link);
        if($where!==null)$db->where($where);
        if($order!==null)$db->order($order);
        $db->limit($start,1);
        return $db->select()->fetch($field);
    }
    
    public function selectRowById($table,$id,$field='id',$where=null){
        $db= new X_mysql_query($table,$this->link);
        return $db->fetchRowId($id, $field, $where);
    }
    
    public function query($query){
        $result = mysql_query($query, $this->link);
        if($result === false) {
            X_debug::$mysql_errors[] = mysql_error($this->link);
        }
        return $result;
    }
    
    public function newQuery($table){
        return new X_mysql_query($table,$this->link);
    }
    
    public function truncate($table){
        return $this->query("TRUNCATE TABLE `".mysql_real_escape_string($table,$this->link)."`;");
    }
    
    public function showTables($recursiveSchema=false){
        $results= $this->query("SHOW TABLES;");
        $tables= array();
        while($table= mysql_fetch_array($results)){
            if($recursiveSchema){
                $tables[$table[0]]= $this->showColumns($table[0]);
            }else{
                $tables[$table[0]]= $table[0];
            }
        }
        return $tables;
    }
    
    public function showColumns($table){
        return $this->newQuery($table)->fetchColumns();
    }
    
    public function configureTables(){
        foreach(X_config::$mysql_tables as $table=>$infos){
            $this->createTable($table, $infos['fields'],$infos['primary'],$infos['specs']);
        }
    }
    
    public function createDatabase($databaseName){
        return mysql_query("CREATE DATABASE IF NOT EXISTS `".mysql_real_escape_string($databaseName,$this->link)."`");
    }
    
    public function createTable($tableName,$columns,$primary="",$specs=""){
        $tableName= mysql_real_escape_string($tableName,$this->link);
        if($primary==="")$primary= (is_array($columns))? key($columns) : "id";
        if(!empty($primary)){
            $primary= mysql_real_escape_string($primary,$this->link);
            if(stripos($columns[$primary],"auto_increment")===false && stripos($columns[$primary],"int")!==false)$columns[$primary] .= " AUTO_INCREMENT";
        }else $primary= "";
        if(is_array($columns)){
            $cols= "";
            foreach($columns as $col=>$type){
                $cols .= (($cols!="")? ",":"")."`".mysql_real_escape_string($col,$this->link)."` ".$type;
            }
        }else $cols= $columns;
        if(!empty($primary) && !empty($cols))$primary= ", PRIMARY KEY(`".$primary."`)";
        $result= $this->query("CREATE TABLE IF NOT EXISTS `".$tableName."`(".$cols.$primary.") ".$specs.";");
        if($result===false && ($results= $this->query("SHOW COLUMNS FROM `".$tableName."`"))){
            $actualColumns= array();
            $dropColumns= "";
            $modifyColumns= "";
            while($actualCol= mysql_fetch_assoc($results)){
                $actualColumns[]= $actualCol['Field'];
                if(array_key_exists($actualCol['Field'],$columns))$modifyColumns .= (($modifyColumns!="")? ",":"")." MODIFY `".mysql_real_escape_string($actualCol['Field'],$this->link)."` ".current(explode(',',$columns[$actualCol['Field']]));
                else $dropColumns .= (($dropColumns!="")? ",":"")." DROP `".mysql_real_escape_string($actualCol['Field'],$this->link)."`";
            }
            $newColumns= "";
            foreach($columns as $col=>$type){
                if(!in_array($col,$actualColumns))$newColumns .= (($newColumns!="")? ",":"")." ADD `".mysql_real_escape_string($col,$this->link)."` ".$type;
            }
            $query= "ALTER TABLE `".$tableName."` ".((!empty($newColumns))? " ".$newColumns:"").((!empty($modifyColumns))? ((!empty($newColumns))? ",":"")." ".$modifyColumns:"").((!empty($dropColumns))? ((!empty($newColumns) || !empty($modifyColumns))? ",":"")." ".$dropColumns:"").((!empty($specs))? ((!empty($newColumns) || !empty($modifyColumns) || !empty($dropColumns))? ",":"")." ".$specs:"");
            $result= $this->query($query);
        }
        return $result;
    }
    
}

/*
class X_mysql_table extends X{
    protected $link;
    protected $table;
    
    public function __construct($table,$link=null){
        if($link===null)$link= X_options::mysql_getLastConnectionLink();
        $this->link= $link;
        $this->table= $table;
        
    }
    
    //TODO: MySQL table
    
    public function __toString(){
        return $this->table;
    }
    
}

class X_mysql_row extends X{
    protected $link;
    protected $table;
    protected $id;
    protected $idField="id";
    
    public function __construct($id,$table,$link=null,$idField="id"){
        if($link===null)$link= X_options::mysql_getLastConnectionLink();
        $this->link= $link;
        $this->table= $table;
        $this->id= $id;
        $this->idField= $idField;
    }
    
    //TODO: MySQL row
    
    public function __toString(){
        return $this->table."#".$this->id;
    }
    
}
*/

class X_mysql_query extends X{
    public $link;
    public $table;
    public $tableName;
    
    protected $select=null;
    protected $join=null;
    protected $update=null;
    protected $insert=null;
    protected $multiInsert=null;
    protected $insertKeys=null;
    protected $insertVals=null;
    protected $delete=false;
    protected $lowercase=false;
    protected $where;
    protected $order=null;
    protected $group=null;
    protected $limit=null;
    protected $resultSet=null;
    protected $tableAS='';
    protected $from=null;
    protected $fromAS=null;
    protected $query= null;
    
    public function __construct($table,$link=null){
        if($link===null)
            $this->link= X_options::mysql_getLastConnectionLink();
        else
            $this->link= $link;
        if(($pos= stripos($table, " as "))){
            $this->tableAS= " AS '".mysql_real_escape_string(preg_replace("#^'(.+)'$#i","$1",substr($table,$pos+4)),$this->link)."'";
            $table= substr($table,0,$pos);
        }
        $this->tableName= $table;
        $this->table= $this->tableName($table);
        $this->where= new X_mysql_whereCondition($this->link);
    }
    
    protected function tableName($table){
        $table= str_replace("`","",$table);
        if(($pos= stripos($table, " as "))){
            $table= substr($table,0,$pos);
        }
        if(strpos($table,".")!==false){
            $table= explode(".",$table,2);
            return "`".mysql_real_escape_string($table[0],$this->link)."`.`".mysql_real_escape_string($table[1],$this->link)."`";
        }else{
            return "`".mysql_real_escape_string($table,$this->link)."`";
        }
    }
    
    protected function keyName($key){
        return "`".mysql_real_escape_string(str_replace("`","",$key),$this->link)."`";
    }
    
    protected function fieldName($field,$table=null){
        if($table===null)$table= $this->tableName;
        $field= strtolower(trim(str_replace("`","",$field)));
        $as= "";
        if(($pos= stripos($field, " as "))){
            $as= " AS '".mysql_real_escape_string(preg_replace("#^'(.+)'$#i","$1",substr($field,$pos+4)),$this->link)."'";
            $field= substr($field,0,$pos);
        }
        if($field!="*"){
            if(strpos($field,".")!==false){
                $field= explode(".",$field,3);
                if(count($field)==3)
                    return "`".mysql_real_escape_string($field[0],$this->link)."`.`".mysql_real_escape_string($field[1],$this->link)."`.".(($field[2]=="*")? $field[2] : "`".mysql_real_escape_string($field[2],$this->link)."`").$as;
                else
                    return "`".mysql_real_escape_string($field[0],$this->link)."`.".(($field[1]=="*")? $field[1] : "`".mysql_real_escape_string($field[1],$this->link)."`").$as;
            }else{
                return $this->tableName($table).".`".mysql_real_escape_string($field,$this->link)."`".$as;
            }
        }
        return $field;
    }
    
    public function select($select="*",$defaultTable=null){
        $this->query= null;
        if($defaultTable===null)$defaultTable=$this->tableName;
        if(is_array($select)){
            $i=0;
            foreach($select as $key=>$val){
                if($val instanceof X_mysql_expr){
                    $this->select .= (($this->select)? ", ":"") . $val;
                }else{
                    $this->select .= (($this->select)? ", ":"") . $this->fieldName($val,$defaultTable);
                }
                if($key!==$i++){
                    $this->select .= " as '".mysql_real_escape_string($key,$this->link)."'";
                }
            }
        }else{
            if($select instanceof X_mysql_expr){
                $this->select .= (($this->select===null)? "":", ") . $select;
            }else{
                $this->select .= (($this->select===null)? "":", ") . $this->fieldName($select,$defaultTable);
            }
        }
        return $this;
    }
    
    public function from($table){
        $this->query= null;
        $table= str_replace("`","",$table);
        if(($pos= stripos($table, " as "))){
            $this->fromAS= " AS '".mysql_real_escape_string(preg_replace("#^'(.+)'$#i","$1",substr($table,$pos+4)),$this->link)."'";
            $this->from= substr($table,0,$pos);
        }
        return $this;
    }
    
    public function join($table,$cond=null,$select=null,$type=""){
        $this->query= null;
        if($cond===null && $type==="")$type="NATURAL";
        $as= '';
        if(($pos= stripos($table, " as "))){
            $as= " AS '".mysql_real_escape_string(preg_replace("#^'(.+)'$#i","$1",substr($table,$pos+4)),$this->link)."'";
            $table= substr($table,0,$pos);
        }
        if($select!==null)$this->select($select,$table);
        $this->join .= " ".$type." JOIN ".$this->tableName($table).$as.(($cond!==null)?" ON ".$cond:"");
        return $this;
    }
    
    public function joinInner($table,$cond,$select=null){
        return $this->join($table,$cond,$select,"INNER");
    }
    public function joinLeft($table,$cond,$select=null){
        return $this->join($table,$cond,$select,"LEFT");
    }
    public function joinRight($table,$cond,$select=null){
        return $this->join($table,$cond,$select,"RIGHT");
    }
    public function innerJoin($table,$cond,$select=null){
        return $this->join($table,$cond,$select,"INNER");
    }
    public function leftJoin($table,$cond,$select=null){
        return $this->join($table,$cond,$select,"LEFT");
    }
    public function rightJoin($table,$cond,$select=null){
        return $this->join($table,$cond,$select,"RIGHT");
    }
    
    public function lowerCase($lowercase= true){
        $this->lowercase= $lowercase;
        return $this;
    }
    
    public function lastInsertId(){
        return mysql_insert_id($this->link);
    }
    
    public function insert($values){
        $this->query= null;
        $this->insert= true;
        if($this->insertVals!==null){
            $this->multiInsert= true;
            if(!is_array($this->insertVals))$this->insertVals= array($this->insertVals);
        }
        if(is_array($values)){
            if(!is_array(current($values))){
                $values= array($values);
            }else $this->multiInsert= true;
            foreach($values as $vals){
                $i=0;
                $insertVals= null;
                foreach($vals as $key=>$val){
                    if($key!==$i++ && $this->insertVals===null){
                        $this->insertKeys .= (($this->insertKeys===null)? "":", ") . $this->keyName($key);
                    }
                    if($val instanceof X_mysql_expr){
                        $insertVals .= (($insertVals===null)? "":", ") . $val;
                    }else{
                        $insertVals .= (($insertVals===null)? "":", ") . "'".mysql_real_escape_string($val,$this->link)."'";
                    }
                }
                if($this->multiInsert){
                    $this->insertVals[]= $insertVals;
                }else{
                    $this->insertVals= $insertVals;
                }
            }
        }else{
            if($this->insertVals===null){
                $this->insertVals= $values;
            }else{
                $this->insertVals[]= $values;
            }
        }
        return $this;
    }
    
    public function delete(){
        $this->query= null;
        $this->delete= true;
        return $this;
    }
    
    /*
     * $order= array('id'=>'ASC','name'=>'DESC')
     */
    public function order($order){
        $this->query= null;
        if(is_array($order)){
            $i=0;
            foreach($order as $key=>$val){
                if($key===$i++){
                    $key= $val;
                    $val= "ASC";
                }
                if($key instanceof X_mysql_expr){
                    $this->order .= (($this->order===null)? "":", ") . $key." ".$val;
                }else{
                    $this->order .= (($this->order===null)? "":", ") . $this->fieldName($key)." ".$val;
                }
            }
        }else{
            if(!empty($order))$this->order= mysql_real_escape_string($order,$this->link);
        }
        return $this;
    }
    
    public function group($group){
        $this->query= null;
        $this->group= $this->fieldName($group);
        return $this;
    }
    
    public function limit($start,$length=null){
        $this->query= null;
        if($length===null){
            $length= (int)$start;
            $start= 0;
        }
        $this->limit= mysql_real_escape_string((int)$start.",".(int)$length,$this->link);
        return $this;
    }
    
    public function update($values){
        $this->query= null;
        if(is_array($values)){
            foreach($values as $key=>$val){
                $this->update .= (($this->update)? ",":"")."`".mysql_real_escape_string($key,$this->link)."`='".mysql_real_escape_string($val,$this->link)."'";
            }
        }else{
            $this->update= $values;
        }
        return $this;
    }
    
    public function where($cond,$escapedVal=null,$escapedVal2=null){
        $this->query= null;
        $this->where->where($cond, $escapedVal, $escapedVal2);
        return $this;
    }
    
    public function orWhere($cond,$escapedVal=null,$escapedVal2=null){
        $this->query= null;
        $this->where->orWhere($cond, $escapedVal, $escapedVal2);
        return $this;
    }
    
    public function fetchColumns(){
        $results= mysql_query("SHOW COLUMNS FROM ".$this->table.";", $this->link);
        $columns= array();
        if($results){
            while($row= mysql_fetch_assoc($results)){
                $columns[current($row)]=$row;
            }
        }
        return $columns;
    }
    
    public function count($field="*"){
        if($this->select===null)$this->select(new X_mysql_expr("COUNT(".$this->fieldName($field).") as 'X_count'"));
        $this->executeQuery();
        if($this->resultSet){
            $row= mysql_fetch_assoc($this->resultSet);
            return (int)$row['X_count'];
        }
        return 0;
    }
    
    public function fetchAll($associative=false){
        $this->resultSet= null;
        if($this->select===null)$this->select();
        $this->executeQuery();
        $resultArray= array();
        if($this->resultSet){
            if($associative!==false){
                if($associative===true){
                    while($result= mysql_fetch_assoc($this->resultSet)) $resultArray[current($result)]= (($this->lowercase)? array_change_key_case($result, CASE_LOWER):$result);
                }else{
                    while($result= mysql_fetch_assoc($this->resultSet)) $resultArray[$result[$associative]]= (($this->lowercase)? array_change_key_case($result, CASE_LOWER):$result);
                }
            }else{
                while($result= mysql_fetch_assoc($this->resultSet)) $resultArray[]= (($this->lowercase)? array_change_key_case($result, CASE_LOWER):$result);
            }
            $this->resultSet= null;
            return $resultArray;
        }
        return false;
    }
    
    public function fetchRow(){
        if($this->select===null)$this->select();
        $this->executeQuery();
        if($this->resultSet){
            $row= mysql_fetch_assoc($this->resultSet);
            if($this->lowercase && is_array($row))return array_change_key_case($row, CASE_LOWER);
            return $row;
        }
        return false;
    }
    
    public function fetchRowId($id, $field='id',$where=null,$cond=null,$escapeVal=null,$escapedVal2=null){
        $this->resultSet= null;
        if($this->select===null)$this->select();
        $this->where($this->fieldName($field)." = ?",$id);
        if($where!==null)$this->where($where,$cond,$escapeVal,$escapedVal2);
        $this->executeQuery();
        if($this->resultSet){
            $row= mysql_fetch_assoc($this->resultSet);
            $this->resultSet= null;
            $this->reset(true, true);
            if($this->lowercase && is_array($row))return array_change_key_case($row, CASE_LOWER);
            return $row;
        }
        $this->reset(true, true);
        return false;
    }
    
    public function fetch($field){
        if($this->select===null)$this->select($field);
        $this->executeQuery();
        if(($results= mysql_fetch_array($this->resultSet))){
            $row= array_change_key_case($results, CASE_LOWER);
            return $row[strtolower($field)];
        }
        return false;
    }
    
    public function fetchWhere($cond, $escapedVal=null, $escapedVal2=null){
        if($this->select===null)$this->select();
        $this->where($cond, $escapedVal, $escapedVal2);
        $this->executeQuery();
        if($this->resultSet){
            $result= mysql_fetch_array($this->resultSet);
            return (($this->lowercase)? array_change_key_case($result, CASE_LOWER):$result);
        }
        return false;
    }
    
    public function fetchToArray($field,$associative=false){
        $this->resultSet= null;
        if($this->select===null)$this->select();
        $this->executeQuery();
        $resultArray= array();
        if($this->resultSet){
            if($associative!==false){
                if($associative===true){
                    while($result= mysql_fetch_assoc($this->resultSet)) $resultArray[current($result)]= $result[strtolower($field)];
                }else{
                    while($result= mysql_fetch_assoc($this->resultSet)) $resultArray[$result[$associative]]= $result[strtolower($field)];
                }
            }else{
                while($result= mysql_fetch_assoc($this->resultSet)) $resultArray[]= $result[strtolower($field)];
            }
            $this->resultSet= null;
            return $resultArray;
        }
        return false;
    }
    
    public function reset($resetAction=false,$resetWhere=false){
        $this->resultSet= null;
        $this->query= null;
        if($resetAction){
            $this->select=null;
            $this->update=null;
            $this->insert=null;
            $this->multiInsert=null;
            $this->delete=false;
            $this->order=null;
            $this->group=null;
            $this->limit=null;
            $this->join=null;
            $this->insertKeys=null;
            $this->insertVals=null;
            $this->from=null;
            $this->fromAS=null;
        }
        if($resetWhere){
            $this->where= new X_mysql_whereCondition($this->link);
        }
        return $this;
    }
    
    public function execute(){
        $return = $this->executeQuery();
        $this->reset(true, true);
        return $return;
    }
    
    public function query($query=null){
        if($query!==null)return $this->query= $query;
        return $this->query= $this->buildStatement();
    }
    
    protected function executeQuery(){
        if($this->resultSet===null && ($query= $this->query)!==null || ($query= $this->buildStatement())){
            return $this->resultSet= mysql_query($query, $this->link) or die(mysql_error()." : ".$query);
        }
    }
    
    protected function buildStatement(){
        $table= $this->table;
        $query= null;
        if($this->multiInsert){
            $values= "";
            foreach($this->insertVals as $insertVals){
                $values .= (($values!="")? ',':'')."(".$insertVals.")";
            }
            $query= "INSERT INTO ".$table.(($this->insertKeys===null)? "":"(".$this->insertKeys.")")." VALUES".$values;
        }else{
            if($this->insert){
                $query= "INSERT INTO ".$table.(($this->insertKeys===null)? "":"(".$this->insertKeys.")")." VALUES(".$this->insertVals.")";
            }else{
                if($this->select!==null){
                    $tableAS= $this->tableAS;
                    if($this->from!==null)$table=$this->from;
                    if($this->fromAS!==null)$tableAS=$this->fromAS;
                    $query= "SELECT ".$this->select." FROM ".$table.$tableAS;
                    if($query!=null && $this->join!==null) $query .= $this->join;
                }
                if($this->update!==null)$query= "UPDATE ".$table." SET ".$this->update;
                if($this->delete)$query= "DELETE FROM ".$table;
                if($query!=null) $query .= " WHERE ".$this->where;
                if($query!=null && $this->group!==null) $query .= " GROUP BY ".$this->group;
                if($query!=null && $this->order!==null) $query .= " ORDER BY ".$this->order;
                if($query!=null && $this->limit!==null) $query .= " LIMIT ".$this->limit;
            }
        }
        return $query;
    }
    
    public function __toString(){
        return (string)$this->buildStatement();
    }
    
}

class X_mysql_expr{
    protected $expr;
    public function __construct($expr) {
        $this->expr= $expr;
    }
    public function __toString() {
        return $this->expr;
    }
}

class X_mysql_whereCondition{
    public $condition= "";
    public $link;
    
    public function __construct($link=null,$cond=null,$escapeVal=null,$escapedVal2=null){
        $this->link= $link;
        if($cond!==null){
            $this->where($cond,$escapeVal,$escapedVal2);
        }
    }
    
    public function where($cond,$escapedVal=null,$escapedVal2=null){
        return $this->addWhereClause($cond,$escapedVal,$escapedVal2);
    }
    
    public function orWhere($cond,$escapedVal=null,$escapedVal2=null){
        return $this->addWhereClause($cond,$escapedVal,$escapedVal2,true);
    }
    
    public function andWhere($cond,$escapedVal=null,$escapedVal2=null){
        return $this->addWhereClause($cond,$escapedVal,$escapedVal2);
    }
    
    protected function addWhereClause($cond,$escapedVal=null,$escapedVal2=null,$or=false){
        if($escapedVal!==null && preg_match("#^[a-z0-9_\.]+$#i", $cond)){
            $cond= "`".str_replace(".","`.`",$cond)."` = ?";
        }
        $maxLoop= 1;
        $initLoop= 0;
        do{
            if($escapedVal !== null){
                if(is_array($escapedVal)){
                    $vals= "";
                    foreach($escapedVal as $val){
                        $vals .= (($vals=="")? '':',').((is_int($val))? '':"'").(($val instanceof X_mysql_expr)? $val : mysql_real_escape_string($val,$this->link)).((is_int($val))? '':"'");
                    }
                    $cond= preg_replace("#\?#",$vals,$cond,1);
                }else{
                    $cond= preg_replace("#\?#",(($escapedVal instanceof X_mysql_expr)? $escapedVal : ((strpos($cond,"'?'")!==false || is_int($escapedVal))? mysql_real_escape_string($escapedVal,$this->link) : "'".mysql_real_escape_string($escapedVal,$this->link)."'")),$cond,1);
                }
            }
            $escapedVal= $escapedVal2;
        }while($initLoop++<$maxLoop);
        $this->condition .= (($this->condition == "")? "":(($or)? " OR " : " AND ")).$cond;
        return $this;
    }
    
    public function __toString(){
        if($this->condition==""){
            return "(1)";
        }else{
            return "(".$this->condition.")";
        }
    }
}
